<?php

namespace app\push\controller;

use Httpful\Request;
use think\Controller;
use think\Db;

class Chat extends Controller
{
    public function contact()
    {
        $input = Request()->param();

        $uid = $input['uid'];
//        $contact_uid = 1;

        if ($uid) {
            /*$msg_list = Db::name('chat c')
                ->field('c.from_uid,from.avatar from_avatar,c.msg')
                ->join('tp_user from', 'c.from_uid = from.id')
                ->where(
                    function ($query) use ($uid, $contact_uid) {
                        $query->where(['c.to_uid' => $uid, 'c.from_uid' => $contact_uid, 'c.is_over' => 0]);
                    }
                )
                ->whereOr(
                    function ($query) use ($uid, $contact_uid) {
                        $query->where(['c.to_uid' => $contact_uid, 'c.from_uid' => $uid, 'c.is_over' => 0]);
                    }
                )
                ->order('c.create_time asc')
                ->select();*/
            $msg_list = Db::name('chat c')
                ->field('c.from_uid,from.avatar from_avatar,c.msg')
                ->join('tp_user from', 'c.from_uid = from.id')
                ->where(
                    function ($query) use ($uid) {
                        $query->where(['c.to_uid' => $uid, 'c.is_over' => 0]);
                    }
                )
                ->whereOr(
                    function ($query) use ($uid) {
                        $query->where(['c.from_uid' => $uid, 'c.is_over' => 0]);
                    }
                )
                ->order('c.create_time asc')
                ->select();

            if ($msg_list) {
                foreach ($msg_list as &$v) {
                    $v['from_avatar'] = doAvatar($v['from_avatar']);
                }
            }
//            Db::name('chat')->where(['to_uid' => $contact_uid, 'from_uid' => $uid, 'is_read' => 0])->setField('is_read', 1);
            Db::name('chat')->where(['to_uid' => $uid, 'is_read' => 0])->setField('is_read', 1);
        }

        // 当前登录用户头像
        $user_info = Db::name('user')->field('id,username,avatar')->where(['id' => $uid])->find();

        // 客服昵称
//        $contact_username = Db::name('user')->where(['id' => $contact_uid])->value('username');

        $this->assign('msg_list', $msg_list ? : []);
        $this->assign('user_info', json_encode($user_info));
//        $this->assign('contact_username', $contact_username);
        $this->assign('uid', $uid);

        return $this->view->fetch();
    }

    // 标识聊天记录结束
    public function msgEnd()
    {
        $input = Request()->param();

        $uid = $input['uid'];

        if (empty($uid)) apiReturn(2, '用户ID缺失');

        Db::name('chat')
            ->where(['from_uid' => $uid])
            ->whereOr(
                function ($query) use ($uid) {
                    $query->where(['to_uid' => $uid]);
                }
            )
            ->setField('is_over', 1);
    }
}
